package filter;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entity.User;
import service.UserService;
import service.impl.UserServiceImpl;


public class SywAutoLoginFilter implements Filter {

    
    public SywAutoLoginFilter() {
        // TODO Auto-generated constructor stub
    }

	public void destroy() {
		// TODO Auto-generated method stub
	}

	
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		request.setCharacterEncoding("utf-8");
		
		HttpServletRequest hsr  = (HttpServletRequest)request;
		HttpServletResponse hsp  = (HttpServletResponse)response;
		User user = (User)hsr.getSession().getAttribute("user");
		
		if (user==null) {
			String cookie_userName = null;
			String cookie_userPwd = null;
			String path = hsr.getServletPath();
			//获取用户名和密码的cookie
			Cookie[] cookies = hsr.getCookies();
			if (cookies!=null) {
				for (Cookie cookie : cookies) {
					if ("cookie_userName".equals(cookie.getName())) {
						cookie_userName = URLEncoder.encode(cookie.getValue(), "utf-8");
					}
					if ("cookie_userPwd".equals(cookie.getName())) {
						cookie_userPwd = URLEncoder.encode(cookie.getValue(), "utf-8");
					}
				}
			}
			if (cookie_userName !=null && cookie_userPwd !=null) {
				UserService us = new UserServiceImpl();
				boolean flag = 
						us.queryUserByLoginNameAndPassword(cookie_userName, cookie_userPwd);
				if (flag) {
					if (!"Login.jsp".equals(path) &&!"/SywUserLoginServlet".equals(path)) {
						hsp.sendRedirect("Login.jsp");
					}else {
						chain.doFilter(request, response);
					}
					hsr.getSession().setAttribute("user", user);
					chain.doFilter(request, response);
					hsp.sendRedirect("Index.html");
				}
				
			}
			
		}
		/*chain.doFilter(request, response);*/
	}

	
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
